package cskevin.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * Http相关工具
 * 包括上传、下载
 * @author csKevin
 * 2013.7.26
 */
public class HttpUtils {
	
	/**
	 * 通过post方式提交字符串信息并得到返回信息
	 * @param url	提交的地址
	 * @param parameter	递交的内容
	 * @return 提交成功返回1 否则返回0
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static HttpEntity postUploading(String url ,String[] key, String...value) throws ClientProtocolException, IOException{
		
		/*
		 * post传送数据必须用NameValuePair[]数组存储
		 */
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for(int i = 0 ; i < value.length ; i++){
			list.add(new BasicNameValuePair(key[i], value[i]));
		}
		HttpPost post = new HttpPost(url);
		post.setEntity(new UrlEncodedFormEntity(list , HTTP.UTF_8));	//发送数据
		
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(post);
		/* 说明服务器已经准备就绪 */
		if(response.getStatusLine().getStatusCode()==200){
			return response.getEntity();
		}
		return null;
	} 
	
	/**
	 * 通过get方式提交字符串信息
	 * @param url	提交的地址
	 * @param parameter	递交的内容
	 * @return 
	 * @return 提交成功返回1 否则返回0
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static HttpEntity getUploading(String url ,String[] key, String...value) throws ClientProtocolException, IOException{
		
		StringBuilder builder = new StringBuilder();
		builder.append(url+"?");
		int tag = value.length-1;
		for (int i = 0; i < value.length; i++) {
			
			builder.append(key[i]);
			builder.append("=");
			builder.append(value[i]);
			if(tag > 0){
				builder.append("&");
				tag--;
			}
		}
		HttpGet get = new HttpGet(builder.toString());
		HttpResponse response = new DefaultHttpClient().execute(get);
		if(response.getStatusLine().getStatusCode()==200){
			return response.getEntity();
		}
		return null;
	} 
	
	/**
	 * 封装从url得到的inputStrem
	 * @param urlString
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public static InputStream getInputStreamFromUrl(String urlString) throws
		MalformedURLException ,IOException{
		URL url= new URL(urlString);
		
		HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
		InputStream inputStream = urlCon.getInputStream();
		return inputStream;
	}
	
	/**
	 * 下载文本文件
	 * @param urlStr
	 * */
	public static String download(String urlStr){
		StringBuffer sbuffer = new StringBuffer();
		BufferedReader buffer =null;
		String line=null;
		try{
			buffer = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(urlStr)));
			while((line = buffer.readLine())!=null){
				sbuffer.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{buffer.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return sbuffer.toString();
	}
	
	/**
	 * 下载其他类型文件并存放在SD卡中
	 * 文件已经存在返回1，文件下载失败返回-1，文件下载成功返回0.
	 * */
	public int downFile(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			SDUtils fileUtils = new SDUtils();
			
			if (fileUtils.isFileExist(path + fileName)) {
				return 1;
			} else {
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.toSDfromInputSteam(fileName, path, inputStream);
				if (resultFile == null) {
					return -1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
}
